/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>


#define PI 3.1415926536f
#include "fluid_shared.h"

#define CUDA_CHECK(call)	\
	do {					\
		if (call!=cudaSuccess) { assert(0 && #call); }			\
	} while (0);


/*struct float4 {
	float x, y, z, w;
	};*/
	
#define GRID_CELL_SIZE	0.1



inline __device__ float frac(float a) {
	return a - floor(a);
}


inline __device__ float4 Vec4Lerp(float4 a, float4 b, float t) 
{
	float4 r;
	r.x = a.x*(1-t) +	b.x*t;
	r.y = a.y*(1-t) +	b.y*t;
	r.z = a.z*(1-t) +	b.z*t;
	r.w = a.w*(1-t) +	b.w*t;
	return r;
}


inline __device__ float4 ReadBuffer(int x, int y, float4 *buffer, int width, int height)
{
	/*if (x<0) x = 0;
	if (y<0) y = 0;
	if (x>=width)  x = width-1;
	if (y>=height) y = height-1;*/
	x &= 0xFF;
	y &= 0xFF;
	return buffer[y * width + x];
}


__device__ float4 ReadBufferLerp(float x, float y, float4 *buffer, int width, int height) 
{
	int ix = x;
	int iy = y;
	float fx = frac(x);
	float fy = frac(y);
	float4 s00 = ReadBuffer(ix+0, iy+0, buffer, width, height);
	float4 s01 = ReadBuffer(ix+0, iy+1, buffer, width, height);
	float4 s11 = ReadBuffer(ix+1, iy+1, buffer, width, height);
	float4 s10 = ReadBuffer(ix+1, iy+0, buffer, width, height);
	float4 s0x = Vec4Lerp(s00, s01, fy);
	float4 s1x = Vec4Lerp(s10, s11, fy);
	return		 Vec4Lerp(s0x, s1x, fx);
}

//
//	CUDA_FluidAdvect
//
__global__ void CUDA_FluidAdvect(float4 *dst, float4 *src, float4 *u_buf, int width, int height, float dt)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
    float4* pixel;
       
	if (x >= width || y >= height) return;
	
	float4 u = ReadBuffer(x, y, u_buf, width, height);
	u.x *= GRID_CELL_SIZE;
	u.y *= GRID_CELL_SIZE;
		
    pixel = (dst + y*width + x);
    pixel[0] = ReadBufferLerp((float)x - u.x * dt/GRID_CELL_SIZE, (float)y - u.y * dt/GRID_CELL_SIZE, src, width, height);
}


//
//
//
__global__ void CUDA_Jacobi(float4 *result, float4 *X, float4 *B, float alpha, float beta)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;
	
	float4 xL = ReadBuffer(x-1, y+0, X, SIZE_X, SIZE_Y);
	float4 xR = ReadBuffer(x+1, y+0, X, SIZE_X, SIZE_Y);
	float4 xB = ReadBuffer(x+0, y-1, X, SIZE_X, SIZE_Y);
	float4 xT = ReadBuffer(x+0, y+1, X, SIZE_X, SIZE_Y);
	float4 bC = ReadBuffer(x, y, B, SIZE_X, SIZE_Y);
	
    pixel = (result + y*SIZE_X + x);
	pixel[0].x = ( xL.x  +  xR.x  +  xB.x  +  xT.x  + alpha * bC.x) / beta;
	pixel[0].y = ( xL.y  +  xR.y  +  xB.y  +  xT.y  + alpha * bC.y) / beta;
	pixel[0].z = ( xL.z  +  xR.z  +  xB.z  +  xT.z  + alpha * bC.z) / beta;
	pixel[0].w = ( xL.w  +  xR.w  +  xB.w  +  xT.w  + alpha * bC.w) / beta;
}


//
//	CUDA_Divergence
//
__global__ void CUDA_Divergence(float4 *result, float4 *W, float dx)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;

	float4 wL = ReadBuffer(x-1, y+0, W, SIZE_X, SIZE_Y);
	float4 wR = ReadBuffer(x+1, y+0, W, SIZE_X, SIZE_Y);
	float4 wB = ReadBuffer(x+0, y-1, W, SIZE_X, SIZE_Y);
	float4 wT = ReadBuffer(x+0, y+1, W, SIZE_X, SIZE_Y);
	
	float div = ((wR.x - wL.x) + (wT.y - wB.y)) / dx / 2.0;
	
    pixel = (result + y*SIZE_X + x);
	pixel[0].x = div;
	pixel[0].y = div;
	pixel[0].z = -div;
	pixel[0].w = 0*div;
}


//
//	CUDA_GradientSubtract
//
__global__ void CUDA_GradientSubtract(float4 *result, float4 *W, float4 *P, float dx)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;

	float pL = ReadBuffer(x-1, y+0, P, SIZE_X, SIZE_Y).x;
	float pR = ReadBuffer(x+1, y+0, P, SIZE_X, SIZE_Y).x;
	float pB = ReadBuffer(x+0, y-1, P, SIZE_X, SIZE_Y).x;
	float pT = ReadBuffer(x+0, y+1, P, SIZE_X, SIZE_Y).x;
	
	float4 new_v;
	new_v = ReadBuffer(x, y, W, SIZE_X, SIZE_Y);
	
	new_v.x -= (pR - pL) / dx;
	new_v.y -= (pT - pB) / dx;
		
    pixel = (result + y*SIZE_X + x);
    
    
    new_v.x *= 1.00000;
    new_v.y *= 1.00000;
    new_v.z *= 1.00000;
    new_v.w *= 1.00000;
	pixel[0] = new_v;
	
}


//
//	CUDA_VisVelocity
//
__global__ void CUDA_VisVelocity(float4 *result, float4 *V, float vel_scale)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;

	float4 new_v;
	new_v = ReadBuffer(x, y, V, SIZE_X, SIZE_Y);
	
    pixel = (result + y*SIZE_X + x);
    
    new_v.x = new_v.x * vel_scale + 0.5;
    new_v.y = new_v.y * vel_scale + 0.5;
    new_v.z = new_v.z * vel_scale + 0.5;
    new_v.w = new_v.w * vel_scale + 0.5;
    
	pixel[0] = new_v;
}


//
//	CUDA_VisPressure
//
__global__ void CUDA_VisPressure(float4 *result, float4 *P)
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;

	float p, p1;
	p1 = p = ReadBuffer(x, y, P, SIZE_X, SIZE_Y).x;
	p = sin(p * 3.14) * sin(p * 3.14);
	p = 1 - p*p*p;
	
    pixel = (result + y*SIZE_X + x);
	pixel[0].x = p;
	pixel[0].y = p;
	pixel[0].z = p;
	pixel[0].w = p;
}


//
//	CUDA_Boundry
//
__global__ void CUDA_Boundry(float4 *X, float scale) 
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= SIZE_X || y >= SIZE_Y) return;
    float4* pixel;
    pixel = (X + y*SIZE_X + x);
    bool bound = false;
    int dx = 0;
    int dy = 0;

    if (x==5)	{ bound = true; dx=+1; } else
    if (y==5)	{ bound = true; dy=+1; } else
    if (x==250)	{ bound = true; dx=-1; } else
    if (y==250)	{ bound = true;	dy=-1; }
    
    if (bound) {
	    float4 v = ReadBuffer(x+dx, y+dy, X, SIZE_X, SIZE_Y);
		pixel[0].x = v.x * scale;
		pixel[0].y = v.y * scale;
		pixel[0].z = v.z * scale;
		pixel[0].w = v.w * scale;
	}
}


//
//	CUDA_FluidSimulate
//
extern "C" 
void CUDA_FluidSimulate(void** surface, int width, int height, size_t pitch, float t, float dt, float vel_scale, float viscosity)
{
    cudaError_t error = cudaSuccess;

	//	Declare BLOCKS :
    dim3 Db = dim3( 8, 8 ); // block dimensions are fixed to be 256 threads
    dim3 Dg = dim3( (width+Db.x-1)/Db.x, (height+Db.y-1)/Db.y );
    
    float4	*buffer_color		=	(float4*)surface[FLUID_COLOR];
    float4	*buffer_velocity	=	(float4*)surface[FLUID_VELOCITY];
    float4	*buffer_pressure	=	(float4*)surface[FLUID_PRESSURE];
    float4	*buffer_vel_vis		=	(float4*)surface[FLUID_VELOCITY_VIS];
    float4	*buffer_temp		=	(float4*)surface[FLUID_TEMP];
    float4	*buffer_temp2		=	(float4*)surface[FLUID_TEMP2];
    float4	*buffer_temp3		=	(float4*)surface[FLUID_TEMP3];
    float4	*buffer_press_vis	=	(float4*)surface[FLUID_PRESSURE_VIS];

	//--------------------------------------------	
    //	ADVECTION :
    //--------------------------------------------	
    for (int i=0; i<1; i++) {
		CUDA_FluidAdvect<<<Dg,Db>>>( buffer_temp, buffer_velocity, buffer_velocity, width, height, dt/1.0 );
		CUDA_CHECK( cudaMemcpy(buffer_velocity, buffer_temp, BUFFER_SIZE, cudaMemcpyDeviceToDevice) );

		CUDA_FluidAdvect<<<Dg,Db>>>( buffer_temp, buffer_color, buffer_velocity, width, height, dt/1.0 );
		CUDA_CHECK( cudaMemcpy(buffer_color, buffer_temp, BUFFER_SIZE, cudaMemcpyDeviceToDevice) );
	}
    
    //--------------------------------------------	
    //	VISCOSITY :
    //--------------------------------------------	
    float alpha = GRID_CELL_SIZE * GRID_CELL_SIZE / viscosity / dt;
    float beta  = 4 + alpha;
    
    CUDA_CHECK( cudaMemset(buffer_temp2, 0x00, BUFFER_SIZE) );
    
    for (int i=0; i<10; i++) {
		CUDA_Jacobi<<<Dg,Db>>>(buffer_temp,  buffer_temp2, buffer_velocity, alpha, beta);
	    CUDA_CHECK( cudaMemcpy(buffer_temp2, buffer_temp,  BUFFER_SIZE, cudaMemcpyDeviceToDevice) );
	}
	
	//--------------------------------------------	
    //	FORCE APPLICATION :
	//--------------------------------------------	
    
	//--------------------------------------------	
    //	PRESSURE :
    //--------------------------------------------	
    alpha = - GRID_CELL_SIZE * GRID_CELL_SIZE;
    beta  = 4;
    
    CUDA_CHECK( cudaMemset(buffer_pressure, 0x00, BUFFER_SIZE) );

	//	NOTE : buffer_temp2 containt intermediate non-divergence-free velocity field.
	//	then, buffer_temp3 will contain divergence.
    CUDA_Divergence<<<Dg,Db>>>( buffer_temp3, buffer_temp2, GRID_CELL_SIZE);
														 
    for (int i=0; i<20; i++) {
		CUDA_Jacobi<<<Dg,Db>>>(buffer_temp,     buffer_pressure, buffer_temp3, alpha, beta);
	    CUDA_CHECK( cudaMemcpy(buffer_pressure, buffer_temp,     BUFFER_SIZE, cudaMemcpyDeviceToDevice) );
	}

	CUDA_GradientSubtract<<<Dg,Db>>>(buffer_velocity, buffer_temp2, buffer_pressure, GRID_CELL_SIZE);
	
	/*CUDA_Boundry<<<Dg,Db>>>(buffer_pressure, +1);
	CUDA_Boundry<<<Dg,Db>>>(buffer_velocity, -1);*/
	
	CUDA_VisVelocity<<<Dg, Db>>>(buffer_vel_vis,   buffer_velocity, vel_scale);
	CUDA_VisPressure<<<Dg, Db>>>(buffer_press_vis, buffer_pressure);

    error = cudaGetLastError();
    if (error != cudaSuccess) {
		assert(0 && "CUDA_FluidSimulate()");
    }
}
